<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2009, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */


// ------------------------------------------------------------------------

/**
 * CodeIgniter Form Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/helpers/form_helper.html
 */

// ------------------------------------------------------------------------

/**
 * Form Declaration
 *
 * Creates the opening portion of the form.
 *
 * @access	public
 * @param	string	the URI segments of the form destination
 * @param	array	a key/value pair of attributes
 * @param	array	a key/value pair hidden data
 * @return	string
 */
if ( ! function_exists('form_open'))
{
	function form_open($action = '', $attributes = '', $hidden = array())
	{
		$CI =& get_instance();

		$charset = strtolower($CI->config->item('charset'));

		if ($attributes == '')
		{
			$attributes = 'method="post" accept-charset="'.$charset.'"';
		}

		else
		{
			if ( is_string($attributes) )
			{
				if(strpos($attributes, 'accept-charset=') === FALSE)
				{
					$attributes .= ' accept-charset="'.$charset.'"';
				}
			}

			elseif ( is_object($attributes) or is_array($attributes) )
			{
				$attributes = (array) $attributes;

				if(!in_array('accept-charset', $attributes))
				{
					$attributes['accept-charset'] = $charset;
				}
			}
		}
		//Add 2 hidden fields for security reason
		$hidden['_form_action'] = $action;
		$hidden['_form_token'] = get_form_token($action);

		$action = ( strpos($action, '://') === FALSE) ? $CI->config->site_url($action) : $action;

		$form = '<form action="'.$action.'"';

		$form .= _attributes_to_string($attributes, TRUE);

		$form .= '>';


		if (is_array($hidden) AND count($hidden) > 0)
		{
			$form .= form_hidden($hidden);
		}

		return $form;
	}
}

if ( ! function_exists('get_form_token'))
{
	/**
	 * Get form token key
	 * @param $action
	 * @return unknown_type
	 */
	function get_form_token($action)
	{
		$CI =& get_instance();
		return sha1($action . $CI->session->get_form_salt());
	}
}

if ( ! function_exists('validate_form_token'))
{
	/**
	 * Validate Form token key
	 * @param $action
	 * @param $form_token
	 * @return unknown_type
	 */
	function validate_form_token($action = '', $form_token = '')
	{
		$CI =& get_instance();
		return $form_token == sha1($action . $CI->session->get_form_salt());
	}
}

if ( ! function_exists('text_editor'))
{
	function text_editor($params = array()){
		$CI =& get_instance();
		switch ($CI->config->item('text_editor')){
			case 'tiny_mce':
				return tinymce($params);
				break;
			case 'ckeditor':
				return ckeditor($params);
				break;
			default:
				return '';
		}
	}
}

if ( ! function_exists('ckeditor'))
{
	function ckeditor($params = array()){
		if (isset($params['id']))
			$id = $params['id'];
		else
			return "";

		if (isset($params['toolbar'])){
			if (strtolower($params['toolbar']) == 'simple'){
				$toolbar = 'basic';
			}else if (strtolower($params['toolbar']) == 'advanced'){
				$toolbar = 'full';
			}
		}else{
			$toolbar = 'Full';
		}

		if (isset($params['content']))
			$text = $params['content'];
		else
			$text = '';

		if (isset($params['width']))
			$width = $params['width'];
		else
			$width = false;

		if (isset($params['height']))
			$height = $params['height'];
		else
			$height = false;

		$option = "{toolbar : '$toolbar'";
		if ($width){
			$option .= ",width:'$width'";
		}
		if ($height){
			$option .= ",height:'$height'";
		}
		$option .= "}";

		return
		"<textarea name='$id' id='$id'>$text</textarea>" .
        "<script type='text/javascript'>" .
			"CKEDITOR.replace('$id',$option);" .
        "</script>";
	}
}
if ( ! function_exists('tinymce'))
{
	function tinymce($params = array()){
		if (isset($params['id']))
			$id = $params['id'];
		else
			return "";

		if (isset($params['toolbar'])){
			if (strtolower($params['toolbar']) == 'basic'){
				$theme = 'simple';
			}else if (strtolower($params['toolbar']) == 'full'){
				$theme = 'advanced';
			}
		}else{
			$theme = 'advanced';
		}
		if (isset($params['content']))
			$text = $params['content'];
		else
			$text = '';

		if (isset($params['width']))
			$width = $params['width'];
		else
			$width = 650;

		if (isset($params['height']))
			$height = $params['height'];
		else
			$height = 450;

		return '<script type="text/javascript">
					tinyMCE.init({
						mode : "exact",
						elements : "'.$id.'",
						width : "'.$width.'",
						height : "'.$height.'",
						theme : "'.$theme.'",
						/* Dùng domain */
						remove_script_host : false,
						convert_urls : true,
						/* Dùng đường dẫn tuyệt đối */
						relative_urls : false,
						verify_html : true,
						cleanup : true,
						language : "vi",
						plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount",
				valid_elements : "a,b,blockquote,br,center,del,div,em,font,h2,h3,h4,i,img,ins,li,hr,ol,p,pre,s,span,strong,strike,sub,sup,table,tbody,td,th,tr,u,ul",
				extended_valid_elements : "a[href|name|rel|style|target|title],b[style],blockquote[style|title],br[clear|title],center[],del[style|title],div[align|style|title],em[style|title],font[color|face|size|style|title],h2[],h3[],h4[],i[style|title],img[align|alt|border|height|hspace|src|style|title|vspace|width],ins[style|title],li[style|title|type],hr[align|noshade|size|style|title],ol[style|title|type],p[align|style|title],pre[style|title],s[style|title],span[style|title],strong[style],strike[style|title],sub[style|title],sup[style|title],table[align|bgcolor|border|bordercolor|cellpadding|cellspacing|height|style|title|width],tbody[],td[align|bgcolor|colspan|height|nowrap|rowspan|style|title|valign|width],th[align|bgcolor|colspan|height|nowrap|rowspan|style|title|valign|width],tr[align|bgcolor|height|nowrap|style|title|valign],u[style|title],ul[style|title|type],",
				invalid_styles : "behavior,background-image,background,list-style-image,expression,/*,*/",

						/* Theme options */
						theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,code,|,preview,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true,
						theme_advanced_resizing_use_cookie : false,
						theme_advanced_path : false,

						content_css : "'.APPPATH_URI.'assets/css/admin/layout.css"
					});
				</script>
				<textarea id="'.$id.'" name="'.$id.'" style="width: '.$width.'px; height:'.$height.'px">'.$text.'</textarea>';
	}
}
/**
 * Create toolbar
 * @param $buttons
 * @return unknown_type
 */
function createToolbar($buttons = array(), $title = array()){
	$CI =& get_instance();
	$output = '<div id="toolbar">';

	$output .= '<span '.$title['attribute'].'>'.$title['label'].'</span>';
	if(!empty($title['action'])) $output .= '<span class="action">['.$title['action'].']</span>';
	$output .= '<div class="button_box">';
	foreach($buttons as $button) {
		$command = $button['command'];
		if (isset($button['label']))
			$label = $button['label'];
		else {
			$label = $button['command'];
			if($CI->lang->line('toolbar_'.$label)){
				$label = $CI->lang->line('toolbar_'.$label);
			}
		}
		$attribute = isset($button['attribute']) ? $button['attribute'] : 'class="btn_admin"';
		if ($command == 'reset'){
			$output .= form_reset($command, $label, $attribute);
		}else{
			$output .= form_submit($command, $label, $attribute);
		}
	}
	$output .= '</div></div>';
	return $output;
}

/**
 * Create Date Range Input with two text box to enter 'from date' and 'to date' in range
 * (which means from date <= to date)
 * @param $params
 * @return unknown_type
 */
function dateInputRange($params = array('from_id'=>'from_date', 'from_text'=>'', 'from_date'=>'','to_id' => 'to_date', 'to_text'=>'', 'to_date'=>'')){
	$script = '<script type="text/javascript">
				    function customRange'. $params['from_id'] . '(input) {
				        return {minDate: (input.id == "'. $params['to_id'] . '" ? $("#'. $params['from_id'] . '").datepicker("getDate") : null),
				            maxDate: (input.id == "' . $params['from_id'] . '" ? $("#' . $params['to_id'] . '").datepicker("getDate") : null)};
				    }
				    $(function(){
				        $("#' . $params['from_id'] . ',#' . $params['to_id'] . '").datepicker({
				            dateFormat: "' . JQUERY_DATE_FORMAT . '",
							showStatus: true,
							changeMonth: true,
							changeYear: true,
				            beforeShow: customRange' . $params['from_id'] . ',
				            showOn: "both",
				            showButtonPanel: true,
				            showAnim: "fadeIn",
				            buttonImage: "' . image_url('../images/calendar.gif') . '",
				            buttonImageOnly: true
				        });
				    });
				</script>';
	$html = '<div class="date_range"><span class="date_range_title">' . $params['from_text'] . '</span><br/><input class="textbox date_range_input" type="text" name="'.$params['from_id'].'" id="'.$params['from_id'].'" value="'.$params['from_date'].'"/></div>';
	$html .= '<div class="date_range"><span class="date_range_title">' . $params['to_text'] . '</span><br/><input class="textbox date_range_input" type="text" name="'.$params['to_id'].'" id="'.$params['to_id'].'" value="'.$params['to_date'].'"/></div>';

	return $script . $html;
}

function fromDateRange($params = array('from_id'=>'from_date', 'from_text'=>'', 'from_date'=>'')){
    $script = '<script type="text/javascript">
                    $(function(){
                        $("#' . $params['from_id'].'").datepicker({
                            dateFormat: "' . JQUERY_DATE_FORMAT . '",
                            showStatus: true,
                            changeMonth: true,
                            changeYear: true,
                            showOn: "both",
                            showButtonPanel: true,
                            showAnim: "fadeIn",
                            buttonImage: "' . image_url('../images/calendar.gif') . '",
                            buttonImageOnly: true
                        });
                    });
                </script>';
    $html = '<div class="date_range"><span class="date_range_title">' . $params['from_text'] . '</span><br/><input class="textbox date_range_input" type="text" name="'.$params['from_id'].'" id="'.$params['from_id'].'" value="'.$params['from_date'].'"/></div>';

    return $script . $html;
}

/**
 * Create Dropdownlist multi Checkbox
 */
function form_dropdown_multi_checkbox($id,$value,$width,$display_id,$display_value,$attribute = "") {

	$checkedFunction = '';
	$checkArr = "";
	if(!is_array($display_value)) {
		$checkArr = explode(';',$display_value);

		for($i=0;$i<count($checkArr);$i++) {
			$checkedFunction .=	 '$("input:checkbox[value=\''.$checkArr[$i].'\']").attr("checked",true);';
		}
	} else {
		if(!empty($display_value)) {
			$checkArr = $display_value;
		}
	}

	for($i=0;$i<count($checkArr);$i++) {
			$checkedFunction .=	 '$("input:checkbox[value=\''.$checkArr[$i].'\']").attr("checked",true);';
		}
	$script = '
		<script type="text/javascript">

		j(document).ready(function(){

			 $("#'.$id.'").dropdownchecklist( {icon: {}, width:'.$width.',
			firstItemChecksAll: true,
		    forceMultiple: true
	        , onComplete: function(selector) {
	            var values = "";
	            for( i=0; i < selector.options.length; i++ ) {
	                if (selector.options[i].selected && (selector.options[i].value != "")) {
	                    if ( values != "" ) values += ";";
	                    values += selector.options[i].value;
	                }
	            }

	          	$("#'.$display_id.'").val(values);
	       	 }

	  		});
	  		 $("INPUT[type=\"checkbox\"]").each(function(i) { $(this).attr("checked",false);});
	  		'.$checkedFunction.'
	  	});
		</script>
	';

	$html = form_dropdown($id, $value,'','id="'.$id.'"'.$attribute);
	$html.= '<input type="hidden" name="'.$display_id.'" id="'.$display_id.'" value="'.$display_value.'" />';
	return $script.$html;
}

/**
 * Create Price Range Input with a dropdown show some range price
 * @param $params
 * @return unknown_type
 */
function form_input_price_range($name, $selected, $priceRange="100000, 200000, 500000, 1000000, 5000000"){
	$arr = explode(',', $priceRange);
	$n = count($arr);
	$html = '<select style="width:auto;" name="'.$name.'", id="'.$name.'">';
	$html .= '<option value="">== Tất cả ==</option>';
	if($selected == '0,'.$arr[0]) $select = 'selected';
	else $select = '';
	$html .= '<option '.$select.' value="0,'.$arr[0].'"> nhỏ hơn '.format_money($arr[0]).' VNĐ </option>';
	for($i=0; $i<$n-1; $i++) {
		$val = $arr[$i].", ".$arr[$i+1];
		if($selected == $val) $select = 'selected';
		else $select = '';
		$html .= '<option '.$select.' value="'.$val.'"> từ '.format_money($arr[$i]).' VNĐ -> '.format_money($arr[$i+1]).' VNĐ </option>';
	}
	if($selected == $arr[$n-1]) $select = 'selected';
	else $select = '';
	$html .= '<option '.$select.' value="'.$arr[$n-1].'" > lớn hơn '.format_money($arr[$n-1]).' VNĐ </option>';
	$html .= '</select>';

	return $html;
}
/**
 * Create Format currency
 * @param $params
 * @return unknown_type
 */
function form_input_currency($textbox_id, $value = '', $callout = '', $attribute = ''){
	$script = '<script type="text/javascript">
					j(document).ready(function(){
						j("#'.$textbox_id.'").bind("keyup", function(){
							initFormatNumber_'. $textbox_id . '();';


					$script.= '	});
						initFormatNumber_'. $textbox_id . '();
					});
					function initFormatNumber_'. $textbox_id .'(){
						j("#detail_'.$textbox_id.'").text(j("#'.$textbox_id.'").val());

						if(j("#'.$textbox_id.'").val() != "") {
							j("#detail_'.$textbox_id.'").format();
						}';
						if ($callout!= '') {
							$script.= '
							if (typeof eval('. $callout .') == "function") {
								'. $callout .'();
							}';
						}
					$script.= '}';
				$script .= 'function numbersonly(myfield, e, dec)
							{
								var key;
								var keychar;

								if (window.event)
								   key = window.event.keyCode;
								else if (e)
								   key = e.which;
								else
								   return true;
								keychar = String.fromCharCode(key);

								// control keys
								if ((key==null) || (key==0) || (key==8) ||
								    (key==9) || (key==13) || (key==27) )
								   return true;

								// numbers
								else if ((("0123456789").indexOf(keychar) > -1))
								   return true;

								// decimal point jump
								else if (dec && (keychar == "."))
								   {
								   myfield.form.elements[dec].focus();
								   return false;
								   }
								else
								   return false;
							}';
				$script .= '</script>';
	$html = '<input style="text-align:right" '.$attribute.' id="'.$textbox_id.'" type="text" value="'.$value.'" name="'.$textbox_id.'"/>' . lang(CURRENT_LANGUAGE . '_currency');

	$html .= '<div style="font-weight:bold; padding-right:3px;" id="detail_'. $textbox_id. '"></div>';
	return $script . $html;
}

/**
 * Generate text area with max length input setting
 * @param $params - array of setting
 * id - id and name of text area
 * max_length - max length input
 * content - content of text area
 * rows - number of rows
 * cols - number of columns
 * @return unknown_type
 */
function form_textarea_max_length($id, $content = '', $max_length = 255, $attribute = 'rows="4" cols="50"'){
	$script = '<script type="text/javascript">j(document).ready(function(){j("#'.$id.'").charCounter('.$max_length.');});</script>';
	$html = '<textarea '.$attribute.'" id="'.$id.'" name="'.$id.'" class="charcounter">'. $content .'</textarea>';

	return $script . $html;
}

/**
 * Form captcha
 * @param $id Trong trường hợp dùng nhiều captcha trên 1 màn hình, các captcha cần có id khác nhau
 * @return unknown_type
 */
function form_captcha($id=''){
	$output = "";
	$output .=
		'<script type="text/javascript">
			function new_captcha'.$id.'() {
				var now = new Date();
				document.images.captcha'.$id.'.src = "' . BASE_URI.'application/captcha/visual-captcha.php?' . '" + now.getTime() + "&id='.$id.'";
			}
		</script>';
	$output .= '<img style="border: solid 1px lightgray;" id="captcha'.$id.'" name="captcha'.$id.'" src="'. BASE_URI.'application/captcha/visual-captcha.php?'.time()."&id=$id" . '" height="48" alt="Visual CAPTCHA" />';
	$output .= '<a href="JavaScript: new_captcha'.$id.'();" tabindex=100><img src="' . BASE_URI.'application/captcha/Refresh_48.png' . '"></img></a>';
	return $output;
}
function form_radio_label($data = '', $value = '', $checked = FALSE,$id='', $label = '',$label_class='clear', $extra = ''){
	return form_radio($data, $value, $checked,"id='$id' $extra") . "<label for='$id' class='$label_class'>$label</label>";
}
/* End of file form_helper.php */
/* Location: ./system/helpers/form_helper.php */